$(function () {
    layui.use(['laydate', 'laytpl', 'table', 'form', 'formSelects', 'layer','soulTable','util'], function () {
        var laydate = layui.laydate,
            laytpl = layui.laytpl,
            table = layui.table,
            form = layui.form,
            formSelects = layui.formSelects,
            layer = layui.layer,
            soulTable = layui.soulTable,
            util = layui.util;
        var areaId = null, flag = 0, allMeters = [], tbIndex = null;
        var devType = '0';
        initAll();

        function initAll() {
            form.val('search',{
                deviceTypeCode: devType
            });
            initDate();
            getAllAreas();
        }

        function initDate() {
            var max = util.toDateString(new Date(), 'yyyy-MM-dd HH:mm:ss');
            var startDate = laydate.render({
                elem: '#startTime'
                , value: new Date()
                , format: 'yyyy-MM-dd'
                , max: max
                , done: function(value, date, endDate){
                    $(".refreshBtn").click();
                }
            });
            var endDate = laydate.render({
                elem: '#endTime'
                , value: new Date()
                , format: 'yyyy-MM-dd'
                , max: max
                , done: function(value, date, endDate){
                    $(".refreshBtn").click();
                }
            });
        }

        function getAllAreas() {
            $.ajax({
                type: "GET",
                url: ctx + "/areaManger/areaAll.do",
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        var getTpl = $('#area-tpl').html();
                        laytpl(getTpl).render(result, function (html) {
                            $('.areaMenu').html(html);
                            form.render();
                            areaId = $('.areaMenu :selected').val();
                            // filterMeters(areaId);
                            getAllMeters();
                        });
                    }
                }
            });
        }

        function getAllMeters() {
            $.ajax({
                type: "GET",
                url: ctx + "/report/getAllMeters.do",
                data: {
                    deviceTypeCode: devType
                },
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        allMeters = result;
                        // getAllAreas();
                        filterMeters(areaId)
                    }
                }
            });
        }

        function filterMeters(areaId) {
            var list = [];
            if(areaId == '0'){
                list = [].concat(allMeters);
            }else{
                list = allMeters.filter(function (item) {
                    return item.areaId === areaId
                })
            }

            let typeMeterArr = list.filter(function (val) {
                return val.deviceTypeCode == devType
            });

            var getTpl = $('#meter-tpl').html();
            laytpl(getTpl).render(typeMeterArr, function (html) {
                $('.meterMenu').html(html);
                formSelects.render('select-meter');
                formSelects.btns('select-meter', ['select', 'remove','reverse'], {show: 'name', space: '10px'});
                formSelects.value('select-meter', 'val');
                var initmeter = typeMeterArr.map(function(item){
                    return item.meterCode
                });
                formSelects.value('select-meter', initmeter);
                $(".refreshBtn").click();
            });
        }

        form.on('select(areaMenu)', function (data) {
            flag = 1;
            $(".multi-meter").html("");
            formSelects.render('select-meter');
            filterMeters(data.value);
        });

        form.on('select(typeMenu)', function (data) {
           // console.log(data.value)
            devType = data.value;
            getAllMeters();
        });

        // 监听设备多选
        formSelects.on('select-meter', function(id, vals, val, isAdd, isDisabled){
            $(".refreshBtn").click();
        }, true);

        //判断权限
        function hasAuth(authCode) {
            var authArray = authStr.split(",");
            if (authArray && authArray.length > 0) {
                for (var i = 0; i < authArray.length; i++) {
                    if (authArray[i].trim() == authCode) {
                        return true;
                    }
                }
            }
            return false;
        }

        function getDatas(datas) {
            $.ajax({
                type: "POST",
                url: ctx + "/exception/queryAll.do",
                data: datas,
                dataType: "json",
                success: function (result) {
                    if (result.code == "000000") {
                        var data = result.data;
                        renderTable(data);
                    }else {
                        layer.alert(result.message);
                    }
                }
            });
        }

        function renderTable(data) {
            var tbHeigth = $('.main-part').height();
            tbIndex = table.render({
                elem: '#excpTable',
                id: 'myTable',
                data: data,
                drag: false,
                heigth: tbHeigth,
                title: '异常信息表',
                cols: [[
                    {field: 'exceptionTime', title: '异常发生时间', templet:'<div>{{ layui.util.toDateString(d.exceptionTime) }}</div>'},
                    {field: 'repairTime', title: '异常恢复时间', templet:'<div>{{ d.repairTime == null ? "" : layui.util.toDateString(d.repairTime) }}</div>'},
                    {field: 'anotherName', title: '设备'},
                    {field: 'title', title: '异常原因'},
                    // {field: 'remark', title: '备注 <i class="layui-icon layui-icon-about tips" title="双击单元格可输入"></i>', edit: 'text'}
                ]
                ],
                page: {
                    layout: ['prev', 'page', 'next', 'count', 'skip', 'limit']
                    , groups: 5 //只显示 5 个连续页码
                    , limit: 15  //每页显示条数
                    , limits: [15, 30, 45, 60]
                },
                loading: true,
                done: function () {
                    $('.layui-table-view > .layui-table-box').height(tbHeigth - 41);
                    $('.layui-table-view > .layui-table-box .layui-table-body').height(tbHeigth - 80);
                    soulTable.render(this);
                }
            });
        }

        // 查询
        $('.searchBtn').click(function(){
            $(".refreshBtn").click();
        });
        $(".refreshBtn").click(function () {
            form.on('submit(search)', function(data){
                // console.log(data.field);
                getDatas(data.field);
                return false;
            });
        });

        // 编辑备注
        table.on('edit(excpTable)', function(obj){
            $.ajax({
                type: "POST",
                url: ctx + "/exception/updateRemark.do",
                data: {'pkid':obj.data.pkid,'remark':obj.data.remark},
                dataType: "json",
                success: function (result) {
                    if (result.code == '000000') {

                    } else {
                        layer.alert(result.message);
                    }
                }
            });
        });

        // 导出excel
        $('.exportBtn').click(function(){
            soulTable.export('myTable',{filename: '设备异常表.xlsx'});
        });

        // 打印
        $('.printBtn').click(function () {
            createPrintTable();
            // 创建iframe，填入需要打印的内容和样式
            var iframe = document.createElement('IFRAME'),
                doc = null,
                style = ["<style>", "body{font-size: 12px; color: #000;}",
                    "table{width: 100%; border-collapse: collapse; border-spacing: 0;}",
                    "th,td{line-height: 20px; padding: 5px 0; border: 1px solid #000; text-align: center; font-size: 12px; color: #000;}",
                    "thead tr th:first-child,tbody tr td:first-child{width:80px}",
                    "a{color: #000; text-decoration:none;}", "*.layui-hide{display: none}", ".ptitle{font-size:16px;font-weight:bold;text-align:center;}" ,"</style>"].join(""),
                printHtml = $($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-header').html()),
                ptitle = $('<div class="ptitle">设备异常表</div>');
            iframe.setAttribute("id", "print-iframe");
            iframe.setAttribute('style', 'position:absolute;width:100%;height:100%;left:0px;top:0px;z-index:1024;background-color:#fff;');
            document.body.appendChild(iframe);
            doc = iframe.contentWindow.document;
            printHtml.append($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-main').find("table").html());
            printHtml.find("th.layui-table-patch").remove();
            printHtml.find(".layui-table-col-special").remove();
            doc.write(style + ptitle.prop("outerHTML") +printHtml.prop("outerHTML"));
            iframe.contentWindow.focus();
            iframe.contentWindow.print();
            iframe.remove();
            $('#printContentBox').empty();
        });

        function createPrintTable() {
            $('#printContentBox').html('<table id="printTb"></table>');
            var temp = tbIndex.config;
            // 所有数据加载为新表格
            table.render({
                elem: '#printTb'
                , data: temp.data
                , cellMinWidth: 48
                , size: 'sm'
                , defaultToolbar: []
                , cols: temp.cols
                , limit: temp.data.length
            })
        }
    });
});
